package com.ruoyi.classai.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.classai.domain.EwcChapter;
import com.ruoyi.classai.domain.EwcClassStudent;
import com.ruoyi.classai.domain.EwcCourseTeacher;
import com.ruoyi.classai.domain.EwcTeacher;
import com.ruoyi.classai.domain.vo.EwcCourseVo;
import com.ruoyi.classai.domain.vo.TodayCourseChapterVo;
import com.ruoyi.classai.service.*;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.common.sms.properties.AliyunSmsProperties;
import com.ruoyi.common.sms.service.AliyunSmsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 教师信息Controller
 * 
 * @author lcj
 * @date 2025-02-27
 */
@Tag(name = "教师信息管理")
@RestController
@RequestMapping("/teacher")
public class EwcTeacherController extends BaseController
{
    @Autowired
    private IEwcTeacherService ewcTeacherService;
    @Autowired
    private AliyunSmsService smsService;
    @Autowired
    private AliyunSmsProperties smsProperties;
    @Autowired
    private IEwcCourseService courseService;
    @Autowired
    private IEwcChapterService chapterService;
    @Autowired
    private IEwcClassStudentService classStudentService;


    /**
     * 查询教师信息列表
     */
    @Operation(summary = "查询教师信息列表",tags = "教师信息管理")
    @RequiresPermissions("classai:teacher:list")
    @GetMapping("/list")
    public TableDataInfo list(String teacherName,String teacherNo,Integer status )
    {
        startPage();
        //学校id
        String schoolId= SecurityUtils.getLoginUser().getSysUser().getSchoolId();
        List<EwcTeacher> list = ewcTeacherService.list(Wrappers.<EwcTeacher>lambdaQuery()
                .like(StringUtils.isNotEmpty(teacherName),EwcTeacher::getTeacherName,teacherName)
                .like(StringUtils.isNotEmpty(teacherNo),EwcTeacher::getTeacherNo,teacherNo)
                .eq(Objects.nonNull(status),EwcTeacher::getStatus,status)
                .eq(StringUtils.isNotEmpty(schoolId),EwcTeacher::getSchoolId,schoolId)
                .select(EwcTeacher::getId,EwcTeacher::getTeacherNo,EwcTeacher::getTeacherName,EwcTeacher::getTeacherPhone,
                        EwcTeacher::getDescription,EwcTeacher::getTitle,EwcTeacher::getGender,EwcTeacher::getPhotoPath,
                        EwcTeacher::getTeacherEmail,EwcTeacher::getStatus));
        return getDataTable(list);
    }

    /**
     * 导出教师信息列表
     */
    @RequiresPermissions("classai:teacher:export")
    @Log(title = "教师信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EwcTeacher ewcTeacher)
    {
        List<EwcTeacher> list = ewcTeacherService.list(Wrappers.query(ewcTeacher));
        ExcelUtil<EwcTeacher> util = new ExcelUtil<>(EwcTeacher.class);
        util.exportExcel(response, list, "教师信息数据");
    }

    /**
     * 获取教师信息详细信息
     */
    @Operation(summary = "获取教师信息详细信息",tags = "教师信息管理")
    @RequiresPermissions("classai:teacher:query")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {

        return AjaxResult.success(ewcTeacherService.getById(id));
    }

    /**
     * 新增教师信息
     */
    @Operation(summary = "新增教师信息",tags = "教师信息管理")
    @RequiresPermissions("classai:teacher:add")
    @Log(title = "教师信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody EwcTeacher ewcTeacher) {
        //根据工号查询是否存在
        EwcTeacher ewcTeacher1=ewcTeacherService.getOne(Wrappers.<EwcTeacher>lambdaQuery().eq(EwcTeacher::getTeacherNo,ewcTeacher.getTeacherNo())
                .eq(EwcTeacher::getStatus,Constants.COMMON_SUCCESS));
        if (Objects.nonNull(ewcTeacher1)){
            return AjaxResult.error("教师工号已存在，不能重复添加");
        }

        ewcTeacher.setPassword(DigestUtil.md5Hex(Constants.INITIAL_PASSWORD));
        ewcTeacher.setSchoolId(SecurityUtils.getLoginUser().getSysUser().getSchoolId());
        return toAjax(ewcTeacherService.save(ewcTeacher));
    }

    /**
     * 修改教师信息
     */
    @Operation(summary = "修改教师信息",tags = "教师信息管理")
    @RequiresPermissions("classai:teacher:edit")
    @Log(title = "教师信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody EwcTeacher ewcTeacher) {

        return toAjax(ewcTeacherService.updateById(ewcTeacher));
    }

    /**
     * 删除教师信息
     */
    @Operation(summary = "删除教师信息",tags = "教师信息管理")
    @RequiresPermissions("classai:teacher:remove")
    @Log(title = "教师信息", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        Arrays.asList(ids).forEach(d->{
            EwcTeacher ewcTeacher=new EwcTeacher();
            ewcTeacher.setId(d);
            ewcTeacher.setStatus(Constants.COMMON_DELETE);
            ewcTeacherService.updateById(ewcTeacher);
        });
        return AjaxResult.success("删除成功");
    }

    /**
     * 查询老师教学单元列表
     * @param teacherId 老师id
     * @param courseName 课程名称
     * @param startTime 开始时间
     * @param endTime 结束时间

     * @return 课程信息
     */
    @Operation(summary = "查询老师教学单元列表",tags = "教师信息管理")
    @GetMapping("/getTeachingUnitList")
    public TableDataInfo getTeachingUnitList(@NotBlank(message = "教师id不能为空") @RequestParam String teacherId,
                                             String courseName,String startTime,String endTime) {
        startPage();
        List<EwcCourseVo> list=courseService.getList(teacherId,courseName,startTime,endTime,null);
        list.forEach(l->{
            if (StringUtils.isNotEmpty(l.getClassId())) {
                //查询学生人数
                l.setStudentNumber(classStudentService.count(Wrappers.<EwcClassStudent>lambdaQuery().eq(EwcClassStudent::getClassId,l.getClassId())
                        .ne(EwcClassStudent::getStatus,Constants.COMMON_DELETE)));
            }
            //统计章节课程
            l.setClassHour(chapterService.count(Wrappers.<EwcChapter>lambdaQuery().eq(EwcChapter::getCourseId,l.getId())
                    .ne(EwcChapter::getStatus,Constants.COMMON_DELETE)));
        });
        return getDataTable(list);
    }


    /**
     * 重置登录密码
     */
    @Operation(summary = "重置登录密码",tags = "教师信息管理")
    @GetMapping(value = "/resetPassword")
    public AjaxResult resetPassword(@NotBlank(message = "教师id不能为空") @RequestParam String teacherId) {
        EwcTeacher teacher=ewcTeacherService.getById(teacherId);
        if (Objects.nonNull(teacher)&&teacher.getStatus()== Constants.COMMON_SUCCESS){
            teacher.setPassword(DigestUtil.md5Hex(Constants.INITIAL_PASSWORD));
            //发送短信
            boolean status=smsService.sendMessage(teacher.getTeacherPhone(),smsProperties.getSmsTemplateCode(),"{\"code\":\"123456\"}");
            if (!status){
                return AjaxResult.error("短信发送失败");
            }
            //重置密码
            ewcTeacherService.updateById(teacher);
            return AjaxResult.success("重置成功");
        }else {
            return AjaxResult.error("老师已停用,不能重置密码");
        }
    }

}
